package com.easemob.helpdesk.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;

import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.easemob.helpdesk.adapter.ChatAdapter;
import com.easemob.helpdesk.adapter.UserChatAdapter;
import com.easemob.helpdesk.bean.MsgChat;
import com.easemob.helpdesk.bean.MsgChatRes;
import com.easemob.helpdesk.bean.OwnerInfoRes;
import com.easemob.helpdesk.utils.CommonUtils;
import com.easemob.helpdesk.utils.DialogUtils;
import com.housekeeperapp.BuildConfig;
import com.housekeeperapp.R;
import com.net.BaseResponse;
import com.net.HKHttpUtils;
import com.net.HKResponseResultCallBack;
import com.net.MsgApiService;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by wsj on 2018/5/22.
 */

public class UserMsgListActivity extends BaseActivityV2{

    private final String TAG = this.getClass().getSimpleName();

    @Override
    protected void initFindView() {
        tvTitle=findViewById(R.id.user_name);

        user_name_addr=findViewById(R.id.user_name_addr);
        llTitleClick=findViewById(R.id.ll_title_click);
        rl_back=findViewById(R.id.rl_back);

        swipeRefreshLayout=findViewById(R.id.chat_swipe_layout);
        mRecyclerView=findViewById(R.id.list);
        ib_refrash=findViewById(R.id.ib_refrash);
        empty_view=findViewById(R.id.empty_view);


    }

    protected TextView tvTitle;

    protected TextView user_name_addr;
    /**
     * 标题和来源的父View
     */
    protected RelativeLayout llTitleClick;

    protected RelativeLayout rl_back;

    /**
     * 加载更多的View
     */
    protected SwipeRefreshLayout swipeRefreshLayout;

    /**
     * 列表View
     */
    protected RecyclerView mRecyclerView;

    protected TextView ib_refrash;

    protected LinearLayout empty_view;

    /**
     * 当前是否正在加载数据
     */
    private boolean isLoadding = false;
    /**
     * 是否有更多的数据
     */
    private boolean haveMoreData = true;

    private int cur_page = 1;


    private String user_phone;

    private String truename;

    private String username;

    private String homeAddress;

    private String wxHeader;
    private String wxOpenid;

    private Dialog pd = null;

    private List<MsgChat> chats;

    public UserChatAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_chat);
        initFindView();

        //获取Intent传过来的数据
        Intent intent = getIntent();
        final long id = intent.getLongExtra("id", 0L);
        user_phone = intent.getStringExtra("phone");
        wxHeader = intent.getStringExtra("wxHeader");
        homeAddress = intent.getStringExtra("homeAddress");
        wxOpenid = intent.getStringExtra("wxOpenid");

        username = intent.getStringExtra("wxname");
        truename = intent.getStringExtra("name");

        tvTitle.setText(truename);
        user_name_addr.setText(homeAddress);

        //创建一个线性布局管理器
        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        mRecyclerView.setLayoutManager(layoutManager);

        chats = new ArrayList<>();

        mAdapter = new UserChatAdapter(this, chats, mRecyclerView);

        showLoading();

        mRecyclerView.setAdapter(mAdapter);

        swipeRefreshLayout.setColorSchemeResources(R.color.holo_blue_bright, R.color.holo_green_dark,
                R.color.holo_orange_light, R.color.holo_red_light);

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        int firstVisibilePosition = layoutManager.findFirstVisibleItemPosition();
                        if (firstVisibilePosition == 0 && !isLoadding && haveMoreData) {
                            loadMoreMsg(id + "#" + wxOpenid);

                        } else {
                            Toast.makeText(UserMsgListActivity.this, getString(R.string.txt_no_more_message), Toast.LENGTH_SHORT).show();
                        }
                        if (swipeRefreshLayout != null){
                            swipeRefreshLayout.setRefreshing(false);
                        }

                    }
                }, 500);
            }
        });

        rl_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        ib_refrash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLoading();
                cur_page = 1;
                loadFirstMsg(id + "#" + wxOpenid);
            }
        });

        loadFirstMsg(id + "#" + wxOpenid);

    }

    public void showLoading(){
        pd = DialogUtils.getLoadingDialog(this, "加载中...");
        pd.show();
    }

    public void hideLoading() {
        if(pd != null && pd.isShowing()){
            pd.dismiss();
        }
    }

    private void loadFirstMsg(String idkey){
        MsgApiService apiService = HKHttpUtils.getMsgApiService();
        retrofit2.Call<BaseResponse<ArrayList<MsgChat>>> call = apiService.messageList(MainActivity.ticket, String.valueOf(MainActivity.userId), idkey, String.valueOf(cur_page), "10");
        call.enqueue(new HKResponseResultCallBack<ArrayList<MsgChat>>() {
            @Override
            public void onSuccess(ArrayList<MsgChat> msgChats) {

                hideLoading();
                chats.clear();

                if(msgChats.isEmpty()){
                    swipeRefreshLayout.setVisibility(View.GONE);
                    empty_view.setVisibility(View.VISIBLE);

                }else{
                    swipeRefreshLayout.setVisibility(View.VISIBLE);
                    empty_view.setVisibility(View.GONE);

                    for (int i = 0; i < msgChats.size(); i++) {
                        if(msgChats.get(i).getDirect().equals("WX")){
                            msgChats.get(i).setAvatar(wxHeader);
                        }
                    }

                    chats.addAll(msgChats);
                    mAdapter.refresh();
                    mAdapter.refreshSelectLast();
                }
            }

            @Override
            public void onGetDataFailed(int cd, String msg) {
                hideLoading();
                swipeRefreshLayout.setRefreshing(false);
                Toast.makeText(UserMsgListActivity.this, "请求失败:"+msg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailed(retrofit2.Call call, Throwable t) {
                hideLoading();
                swipeRefreshLayout.setRefreshing(false);
                Toast.makeText(UserMsgListActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
            }
        });
//        OkHttpClient okHttpClient = new OkHttpClient();
//
//        System.out.println("initData: " + String.valueOf(MainActivity.ticket));
//
//        RequestBody body = new FormBody.Builder()
//                .add("fromInfo", idkey)
//                .add("page", String.valueOf(cur_page))
//                .add("pagesize", String.valueOf(10))
//                .build();
//
//        Request request = new Request.Builder()
//                .url(BuildConfig.MSG_URL + "message/list")
//                .addHeader("t", String.valueOf(MainActivity.ticket))
//                .addHeader("user_id", String.valueOf(MainActivity.userId))
//                .post(body)
//                .build();
//
//        Call call = okHttpClient.newCall(request);
//
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                e.printStackTrace();
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                    hideLoading();
//                    swipeRefreshLayout.setRefreshing(false);
//                    Toast.makeText(UserMsgListActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
//                    }
//                });
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//
//                final String res = response.body().string();
//                try{
//                    final MsgChatRes result = CommonUtils.parseJsonWithGson(res, MsgChatRes.class);
//
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            hideLoading();
//                            chats.clear();
//                            ArrayList<MsgChat> msgs = result.getData();
//
//                            if(msgs.isEmpty()){
//                                swipeRefreshLayout.setVisibility(View.GONE);
//                                empty_view.setVisibility(View.VISIBLE);
//
//                            }else{
//                                swipeRefreshLayout.setVisibility(View.VISIBLE);
//                                empty_view.setVisibility(View.GONE);
//
//                                for (int i = 0; i < msgs.size(); i++) {
//                                    if(msgs.get(i).getDirect().equals("WX")){
//                                        msgs.get(i).setAvatar(wxHeader);
//                                    }
//                                }
//
//                                chats.addAll(msgs);
//                                mAdapter.refresh();
//                                mAdapter.refreshSelectLast();
//                            }
//
//                        }
//                    });
//                }catch (Exception e){
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            hideLoading();
//                            swipeRefreshLayout.setRefreshing(false);
//                            Toast.makeText(UserMsgListActivity.this, "请求异常", Toast.LENGTH_SHORT).show();
//                        }
//                    });
//                }
//            }
//        });
    }

    private void loadMoreMsg(String idkey){
        MsgApiService apiService = HKHttpUtils.getMsgApiService();
        cur_page++;
        retrofit2.Call<BaseResponse<ArrayList<MsgChat>>> call = apiService.messageList(MainActivity.ticket, String.valueOf(MainActivity.userId), idkey, String.valueOf(cur_page), "10");
        call.enqueue(new HKResponseResultCallBack<ArrayList<MsgChat>>() {
            @Override
            public void onSuccess(ArrayList<MsgChat> msgChats) {
                if (msgChats!= null) {
                    if (msgChats.isEmpty()) {
                        haveMoreData = false;
                        Toast.makeText(UserMsgListActivity.this, getString(R.string.txt_no_more_message), Toast.LENGTH_SHORT).show();
                    } else {

                        for (int i = 0; i < msgChats.size(); i++) {
                            if (msgChats.get(i).getDirect().equals("WX")) {
                                msgChats.get(i).setAvatar(wxHeader);
                            }
                        }

                        chats.addAll(0, msgChats);

                        mAdapter.refresh();
                    }
                    if (swipeRefreshLayout != null) {
                        swipeRefreshLayout.setRefreshing(false);
                    }
                    isLoadding = false;
                }
            }

            @Override
            public void onGetDataFailed(int cd, String msg) {
                isLoadding = false;
                swipeRefreshLayout.setRefreshing(false);
                Toast.makeText(UserMsgListActivity.this, "请求失败:"+msg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailed(retrofit2.Call call, Throwable t) {
                isLoadding = false;
                swipeRefreshLayout.setRefreshing(false);
                Toast.makeText(UserMsgListActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
            }
        });

//        OkHttpClient okHttpClient = new OkHttpClient();
//        cur_page++;
//
//        RequestBody body = new FormBody.Builder()
//                .add("fromInfo", idkey)
//                .add("page", String.valueOf(cur_page))
//                .add("pagesize", String.valueOf(10))
//                .build();
//
//        Request request = new Request.Builder()
//                .url(BuildConfig.MSG_URL + "message/list")
//                .addHeader("t", String.valueOf(MainActivity.ticket))
//                .addHeader("user_id", String.valueOf(MainActivity.userId))
//                .post(body)
//                .build();
//
//        Call call = okHttpClient.newCall(request);
//
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                e.printStackTrace();
////                hideLoading();
//                isLoadding = false;
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        swipeRefreshLayout.setRefreshing(false);
//                        Toast.makeText(UserMsgListActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
//                    }
//                });
//
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//
//                final String res = response.body().string();
//                try{
//                    final MsgChatRes result = CommonUtils.parseJsonWithGson(res, MsgChatRes.class);
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//
//                            if (result.getData().isEmpty()){
//                                haveMoreData = false;
//                                Toast.makeText(UserMsgListActivity.this, getString(R.string.txt_no_more_message), Toast.LENGTH_SHORT).show();
//                            }else{
//                                ArrayList<MsgChat> msgs = result.getData();
//                                for (int i = 0; i < msgs.size(); i++) {
//                                    if(msgs.get(i).getDirect().equals("WX")){
//                                        msgs.get(i).setAvatar(wxHeader);
//                                    }
//                                }
//
//                                chats.addAll(0,msgs);
//
//                                mAdapter.refresh();
//                            }
//                            if (swipeRefreshLayout != null){
//                                swipeRefreshLayout.setRefreshing(false);
//                            }
//                            isLoadding = false;
//                        }
//                    });
//                }catch (Exception e){
//                    isLoadding = false;
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            swipeRefreshLayout.setRefreshing(false);
//                            Toast.makeText(UserMsgListActivity.this, "请求异常", Toast.LENGTH_SHORT).show();
//                        }
//                    });
//                }
//
//
//            }
//        });
    }

}
